//
//  SNMainViewController.swift
//  sinaWeBoo
//
//  Created by Fly on 15/10/16.
//  Copyright © 2015年 Fly. All rights reserved.
//

import UIKit

class SNMainViewController: UITabBarController {

    override func viewDidLoad() {
        super.viewDidLoad()
        //添加子控制器
        addChildViewControllers()
    }
    
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        
        // view appear ->set the property of composeBtn
        setComposeBtn()
    }
    
    // lazy load the compose button
    lazy var composeBtn: UIButton = UIButton(imageName: "tabbar_compose_icon_add",
        backImage: "tabbar_compose_button")
}

// MARK: - 添加tabBar的子控制器
extension SNMainViewController{
    
    // 添加 撰写按钮
    func setComposeBtn() {
        // 添加 事件处理
        composeBtn.addTarget(self, action: "composeClicked", forControlEvents: UIControlEvents.TouchUpInside)
        // 计算缩进 尺寸
        let count = childViewControllers.count
        let width = tabBar.bounds.width / CGFloat(count) - 1
        
        composeBtn.frame = CGRectInset(tabBar.bounds, width * 2, 0)
        tabBar.addSubview(composeBtn)
        
        composeBtn.bringSubviewToFront(tabBar)
    }
    
    // 监听按钮点击的 私有方法，需要加@objc
    @objc private func composeClicked(){
        print("compose btn clicked ")
    }
    
    // 初始化所有子控制器
    func addChildViewControllers() {
        //添加home
        addChildViewController("主页", imageName: "tabbar_home", vc: SNHomeViewController())//style: UITableViewStyle.Grouped))
        //add discover
        addChildViewController("发现",
            imageName: "tabbar_discover",
            vc: SNDiscoverViewController())//(style: UITableViewStyle.Grouped))
        // add 空item，用于放置compose按钮
        addChildViewController(UIViewController())
        
        // add message
        addChildViewController("消息",
            imageName: "tabbar_message_center",
            vc: SNMessageViewController())//style: UITableViewStyle.Grouped))
        //add profile
        addChildViewController("我", imageName: "tabbar_profile", vc: SNProfileViewController())//style: UITableViewStyle.Grouped))
        // 设置图片渲染颜色，可以不使用图片，提高应用的性能
        tabBar.tintColor = UIColor.orangeColor()
    }
    // 添加 一个子控制器
    func addChildViewController(title: String,imageName: String,vc: UITableViewController) {
        // 创建各个导航控制器
        vc.title = title
        vc.tabBarItem.image = UIImage(named: imageName)
        
        let nav = UINavigationController(rootViewController: vc)
       
        
        addChildViewController(nav)
    }
}